<script setup lang="ts">
import {NTree} from 'naive-ui'
import {onMounted, ref} from 'vue'
import type {Api} from '@/api/type'
import BaseApi from '@/api/base-api'

type R<T> = Api.Common.R<T>;
type Data = Api.System.Route;

const baseApi = new BaseApi<Data>('route')

interface Option {
    key: string
    label: string
    parent: string
    children?: Array<Option>
}

const routeTree = ref<Array<Option>>([])

/**
 * 组装用户路由树
 */
const generateTree = (list: Array<Data>): Array<Option> => {
    let optionList: Array<Option> = JSON.parse(JSON.stringify(list))
        .filter((item: Data) => {
            return item.type == 1 || item.type == 2
        })
        .map((item: Data): Option => {
            return {
                key: item.identity,
                label: item.name,
                parent: item.parent
            } as Option
        })

    let _map: Map<string, Option> = optionList.reduce((map: Map<string, Option>, item: Option) => {
        map.set(item.key, item)
        return map
    }, new Map<string, Option>())

    optionList.forEach((item: Option) => {
        let parent: Option | undefined = _map.get(item.parent)
        let current: Option | undefined = _map.get(item.key)
        if (parent) {
            if (!parent?.children) {
                parent.children = []
            }
            if (current) {
                parent.children.push(current)
            }
            _map.set(item.parent, parent)
        }
    })
    return optionList.filter((item: Option): boolean => item.parent == '0')
}

async function initialize() {
    let result: R<Array<Data>> = await baseApi.getDataList()
    if (result.code == 0) {
        routeTree.value = generateTree(result.data || [])
    }
}

onMounted(() => {
    initialize()
})
</script>

<template>
    <n-tree block-line default-expand-all :data="routeTree" />
</template>
